﻿using Qiniu.Auth.digest;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Qiniu.Conf;
using Qiniu.FileOp;
using Qiniu.IO;
using Qiniu.IO.Resumable;
using Qiniu.RPC;
using Qiniu.RS;
using Qiniu.RSF;

namespace SJL.Plugin.Third
{
    internal class QiniuHelper
    {
        private static readonly string cdnPath = "/cdnPath/";
        public static string bucket = "loan";
        public static readonly string Domain = "img.imguang.wang";
        public static readonly string ImageUrlPredix = "http://img.imguang.wang/";
        public static void Init()
        {
            //设置权限key
            Config.ACCESS_KEY = "";
            //设置密匙key
            Config.SECRET_KEY = "";
        }

     


        /// <summary>
        /// 普通上传文件
        /// key必须采用utf8编码，如使用非utf8编码访问七牛云存储将反馈错误
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="key">上传后的路径</param>
        /// <param name="fname">要上传的文件路径（文件必须存在）</param>
        public static PutRet PutFile(string key, string fname)
        {
            if (key.IndexOf('.') == -1) key += Path.GetExtension(fname);
            var policy = new PutPolicy(bucket, 3600);
            string upToken = policy.Token();
            PutExtra extra = new PutExtra();
            IOClient client = new IOClient();
            PutRet ret = client.PutFile(upToken, key, fname, extra);
            return ret;
        }
        /// <summary>
        /// 普通上传图片
        /// key必须采用utf8编码，如使用非utf8编码访问七牛云存储将反馈错误
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="key">上传后的路径</param>
        /// <param name="fname">要上传的文件路径（文件必须存在）</param>
        public static PutRet PutImage(string key, string fname, string mimeType = "image/jpg")
        {
            if (key.IndexOf('.') == -1) key += Path.GetExtension(fname);
            if (mimeType == "") mimeType = GetMimeTypeByExtension(Path.GetExtension(fname));
            var policy = new PutPolicy(bucket, 3600);
            string upToken = policy.Token();
            PutExtra extra = new PutExtra
            {
                MimeType = mimeType,
                Crc32 = 123,
                CheckCrc = CheckCrcType.CHECK,
                Params = new Dictionary<string, string>()
            };
            IOClient client = new IOClient();
            PutRet ret = client.PutFile(upToken, key, fname, extra);
            return ret;
        }
        /// <summary>
        /// 删除单个文件
        /// </summary>
        /// <param name="bucket">文件所在的空间名</param>
        /// <param name="key">文件key</param>
        public static CallRet Delete(string bucket, string key)
        {
            bool re = false;
            //Console.WriteLine("\n===> Delete {0}:{1}", bucket, key);
            RSClient client = new RSClient();
            CallRet ret = client.Delete(new EntryPath(bucket, key));
            return ret;
        }
        /// <summary>
        /// 上传文件到网站服务器，再上传到七牛服务器
        /// </summary>
        /// <param name="fileData">页面/swf传过来的文件数据</param>
        /// <param name="fileType">预留</param>
        /// <param name="path">文件加逻辑路径，如：images/ </param>
        /// <param name="isOriginal">是否保留文件原名</param>
        /// <param name="prefix">不保留原名时，文件名的前缀部分</param>
        /// <returns></returns>
        public static PutRet UploadFile(HttpPostedFileBase fileData, string fileType = "", string path = "", string isOriginal = "", string prefix = "")
        {
            PutRet ret = null;
            if (fileData != null)
            {

                var fileExt = Path.GetExtension(fileData.FileName);
                var fileName = "";
                if (isOriginal != "1")
                {
                    fileName = "test";// DataHelper.CreateRandomName(fileExt);
                    if (prefix != "") fileName = prefix + fileName;
                }
                else fileName = Path.GetFileName(fileData.FileName).Replace(" ", "");

                var fileFullPath = "";
                bool isImage = false;
                string mimeType = GetMimeTypeByExtension(fileExt);
                if (mimeType == "")
                {
                    if (path.Len() == 0) path = "files/";
                    fileFullPath = Path.Combine(path, fileType);
                }
                else if (mimeType.StartsWith("image"))
                {
                    if (path.Len() == 0) path = "images/";
                    fileFullPath = Path.Combine(path, fileType);
                    isImage = true;
                }
                else
                {
                    if (path.Len() == 0) path = "other/";
                    fileFullPath = Path.Combine(path, fileType);
                }
                if (!Directory.Exists(cdnPath + fileFullPath))
                {
                    Directory.CreateDirectory(cdnPath + fileFullPath);
                }
                var fileFullName = cdnPath + fileFullPath + "/" + fileName;
                fileData.SaveAs(fileFullName);

                string key = string.Empty;
                //上传图片到七牛
                if (System.IO.File.Exists(fileFullName))
                {
                    // long len = fileData.ContentLength / 1024;
                    key = fileFullName.Replace(cdnPath, "").Replace("\\", "/").Replace("//", "/");
                    if (isImage) ret = PutImage(key, fileFullName, mimeType);
                    else ret = PutFile(key, fileFullName);
                }
            }
            return ret;
        }

        /// <summary>
        /// 通过后缀获取mime类型
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        private static string GetMimeTypeByExtension(string extension)
        {
            string mimeType = "";
            extension = extension.TrimStart('.').ToLowerInvariant();
            switch (extension)
            {
                case "gif":
                    mimeType = "image/gif";
                    break;
                case "png":
                    mimeType = "image/png";
                    break;
                case "bmp":
                    mimeType = "image/bmp";
                    break;
                case "jpeg":
                case "jpg":
                    mimeType = "image/jpg";
                    break;

            }
            return mimeType;
        }

        /// <summary>
        /// 断点续传
        /// </summary>
        /// <param name="bucket"></param>
        /// <param name="key"></param>
        /// <param name="fname"></param>
        public static void ResumablePutFile(string bucket, string key, string fname)
        {
            Console.WriteLine("\n===> ResumablePutFile {0}:{1} fname:{2}", bucket, key, fname);
            PutPolicy policy = new PutPolicy(bucket, 3600);
            string upToken = policy.Token();
            Settings setting = new Settings();
            ResumablePutExtra extra = new ResumablePutExtra();
            // extra.Notify += PutNotifyEvent;//(int blkIdx, int blkSize, BlkputRet ret);//上传进度通知事件
            ResumablePut client = new ResumablePut(setting, extra);
            client.PutFile(upToken, fname, Guid.NewGuid().ToString());
        }

        /// <summary>
        /// 得到文件的外链地址 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isPublic"></param>
        /// <returns></returns>
        public static string GetUrl(string key, bool isPublic = true)
        {
            string baseUrl = GetPolicy.MakeBaseUrl(Domain, key);
            if (isPublic) return baseUrl;
            string private_url = GetPolicy.MakeRequest(baseUrl);
            return private_url;
        }

        /// <summary>
        /// 获取图片信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="isPublic"></param>
        /// <returns></returns>
        public static ImageInfoRet GetImageInfo(string key, bool isPublic = true)
        {
            string url = GetPolicy.MakeBaseUrl(Domain, key);
            //生成fop_url
            string imageInfoURL = ImageInfo.MakeRequest(url);
            //对其签名，生成private_url。如果是公有bucket此步可以省略
            if (!isPublic) imageInfoURL = GetPolicy.MakeRequest(imageInfoURL);
            ImageInfoRet infoRet = ImageInfo.Call(imageInfoURL);
            if (infoRet.OK)
            {
                Console.WriteLine("Format: " + infoRet.Format);
                Console.WriteLine("Width: " + infoRet.Width);
                Console.WriteLine("Heigth: " + infoRet.Height);
                Console.WriteLine("ColorModel: " + infoRet.ColorModel);
            }
            else
            {
                Console.WriteLine("Failed to ImageInfo");
            }
            return infoRet;
        }

        public static string GetImagePreviewUrl(string key, bool isPublic = true)
        {
            string url = GetPolicy.MakeBaseUrl(Domain, key);

            ImageView imageView = new ImageView { Mode = 0, Width = 200, Height = 200, Quality = 90, Format = "jpg" };
            string viewUrl = imageView.MakeRequest(url);
            if (!isPublic) viewUrl = GetPolicy.MakeRequest(viewUrl);//私链
            return viewUrl;
        }

       

      
    }

}
